package main

import (
	"context"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/client"
	"github.com/docker/go-connections/nat"
	"time"
)

func main() {
	envClient, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	ctx := context.Background()
	// 创建容器
	create, err := envClient.ContainerCreate(
		ctx,
		&container.Config{
			Image: "mongo", // 使用的镜像
			ExposedPorts: nat.PortSet{ // 镜像端口
				"27017/tcp": {},
			},
		}, &container.HostConfig{
			PortBindings: nat.PortMap{
				"27017/tcp": []nat.PortBinding{ // 映射端口
					{
						HostIP:   "127.0.0.1",
						HostPort: "0",
					},
				},
			},
		}, nil, nil, "")

	if err != nil {
		panic(err)
	}

	err = envClient.ContainerStart(ctx, create.ID, types.ContainerStartOptions{}) // 启动容器
	if err != nil {
		panic(err)
	}

	inspect, err := envClient.ContainerInspect(ctx, create.ID)
	if err != err {
		panic(err)
	}

	fmt.Printf("listenig at %+v", inspect.NetworkSettings.Ports["27017/tcp"][0])

	time.Sleep(5 * time.Second)
	err = envClient.ContainerRemove(ctx, create.ID, types.ContainerRemoveOptions{ // 删除容器
		Force: true,
	})

	if err != nil {
		panic(err)
	}
	fmt.Println("end")
}
